<template>
  <div class="app-container" id="role">
    <el-form :inline="true" :model="queryForm" class="demo-form-inline">
      <el-form-item label="角色名称:">
        <el-input v-model="queryForm.rolename" placeholder="请输入角色名称" clearable />
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="queryForm.indatetime"
          type="date"
          placeholder="创建时间"
          clearable
        />
        </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="fetchTableData">查询</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8" style="margin-bottom: 10px;">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Plus"
            size="small"
            @click="handleAdd"
          >新增</el-button>
        </el-col>
    
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="Delete"
            size="small"
            :disabled="multiple"
            @click="handleDelete"
          >删除</el-button>
        </el-col>    
        </el-row>

    <!-- 数据表格 -->
    <el-table :data="tableData" style="width: 100%;" :header-cell-style="{ backgroundColor: '#F8F8F8' }" :height="tableHeight"
     border  @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column label="序号" width="55" align="center">
        <template v-slot="scope">
          {{ (queryForm.pageNum - 1) * queryForm.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column property="rolename" label="角色名称" align="center"/>
      <el-table-column property="menulist" label="分配菜单" show-overflow-tooltip align="center">
        <template #default="scope">
            <!-- 使用 computed 方法处理 menulist 显示的内容 -->
          <span>{{ getMenuLabels(scope.row.menulist) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建日期" align="center">
        <template #default="scope">{{ scope.row.indatetime }}</template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
            <el-button type="primary" @click="handleDelete(scope.row)">
              <el-icon style="vertical-align: middle">
               <Delete />
              </el-icon>
              <span style="vertical-align: middle"> 删 除 </span>
            </el-button>
            <el-button type="primary" @click="handleEdit(scope.row)">
              <el-icon style="vertical-align: middle">
              <Edit />
              </el-icon>
              <span style="vertical-align: middle"> 修 改 </span>
            </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin-top:20px; display:flex; align-items:center; justify-content:right;">
      <el-select v-model="queryForm.pageSize" @change="handlePageSizeChange" style="width: 100px; margin-right: 10px">
        <el-option label="10条/页" :value="10" />
        <el-option label="20条/页" :value="20" />
        <el-option label="50条/页" :value="50" />
        <el-option label="100条/页" :value="100" />
      </el-select>
      <el-pagination
        v-show="total > 0"
        :total="total"
        :page-size="queryForm.pageSize"
        :current-page="queryForm.pageNum"
        layout="total, prev, pager, next, jumper"
        @current-change="handlePagination"
      />
    </div>

    <!-- 新增、编辑框 -->
    <el-dialog :title="data.title" v-model="data.open" width="500px" :close-on-click-modal="false" append-to-body>
      <el-form  ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="rolename">
          <el-input v-model="form.rolename" />
        </el-form-item>
        <el-form-item label="菜单分配" prop="menulist">
          <el-checkbox  @change="handleCheckedTreeNodeAll($event, 'permission')">全选/全不选</el-checkbox>
          <el-checkbox style="display: none;" v-model="form.permissionCheckStrictly" @change="handleCheckedTreeConnect($event, 'permission')">父子联动</el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-tree
            class="tree-border"
            :data="data.permissionOptions"
            show-checkbox
            ref="permissionRef"
            node-key="id"
             :check-strictly="false"
            empty-text="加载中，请稍候"
            :props="permissionProps"
          >
            <!-- 通过scoped slots自定义显示内容 -->
            <template v-slot:default="{ node, data }">
              <span @click="handlePermissionNodeClick(node, data)">{{ data.label }}</span>
            </template>
          </el-tree>
      </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
       <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="onSubmit">保 存</el-button>
          <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted, nextTick } from 'vue'
import { Search, Plus } from '@element-plus/icons-vue'
import { getMenuList, getUserMenuList} from '@/api/system/menu.js'
import { getRoleList, addRole,delRole,editRole } from '@/api/system/role.js'
import { ElMessageBox, ElMessage } from 'element-plus';

const queryForm = reactive({
  rolename: '',
  indatetime: '',
  pageNum: 1,
  pageSize: 10
})

// 创建响应式数据
const ids = ref([]) // 多选框选中的 id
const single = ref(false) // 是否为单选
const multiple = ref(true) // 是否为多选
const formRef = ref(null);

// 处理选择变更的函数
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.rolecode)
  single.value = selection.length !== 1
  multiple.value = selection.length === 0
}
    
// 定义表单数据
const form = reactive({
  rolename: '',
  permissionCheckStrictly:true,
})

// 定义校验规则
const rules = reactive({
  rolename: [
    { required: true, message: '角色名称不能为空', trigger: 'blur' },
    { min: 3, max: 10, message: '角色名称长度在 3 到 10 个字符', trigger: 'blur' }
  ]
})

const data = reactive({
  doType: '',
  open: false,
  title: '',
  permissionOptions: [],
  menuNodeAll: false,
  menuNodeAll: false // 添加 menuNodeAll
})

const total = ref(0)
const open = ref(false)
const tableData = ref([])
const permissionRef = ref(null)
const permissionProps = reactive({
  label: 'label',
  children: 'children',
  disabled: 'disabled',
  key: 'id'
})

const tableHeight = ref("385px")

const fetchTableData = async () => {
  try {
    // 获取角色列表
    const res = await getRoleList(queryForm);  
    tableData.value = res.rows;
    total.value = res.total;
  } catch (error) {
    console.error('获取角色列表失败:', error);  
  }
}

// 在组件挂载后获取数据
onMounted(() => {
  getAllMenuList().then(() => {
    fetchTableData()
  })
  // tableHeight.value = window.innerHeight - 250 + "px"; // 计算表格高度
})

const getMenuLabels = (menulist) => {
  if (!menulist) return ''
  // 将 menulist 字符串拆分为数组
  const menuIds = menulist.split(',')
  // 辅助函数：在 permissionOptions 的 children 中查找菜单项
  const findMenuLabelInChildren = (id, options) => {
    for (let option of options) {
      // 查找该 option 的 children 是否有匹配的 id
      if (option.children) {
        const child = option.children.find(child => String(child.id) === String(id))
        if (child) {
          return child.label // 返回子菜单的 label
        }
      }
    }
    return '' // 如果没有找到，返回空字符串
  }

  // 根据菜单 ID 查找 label
  const labels = menuIds.map(id => {
    // 查找菜单项的 label
    const label = findMenuLabelInChildren(id, data.permissionOptions)
    return label
  })
  // 返回所有标签，使用逗号分隔
  return labels.join(', ')
}
 
//打开新增窗口
const handleAdd = async () => {
  data.open = true
  await nextTick();
  data.title = "新增"
  data.doType = "add"
  permissionRef.value?.setCheckedKeys([]);
  form.rolename = ''
  form.remark = ''
}

const handleDelete = async (row) => {
  try {
    const rolecodes = row.rolecode || ids.value;
    await ElMessageBox.confirm('是否确认删除所选用户？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });
    
  const res = await delRole(rolecodes);
  await fetchTableData();
   if(res.code == 200){
      ElMessage.success(res.rows); 
   };

  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error("删除失败" + error);
    }
  }
}

//处理新增和编辑逻辑
const onSubmit = async () => {
  formRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.error("请正确填写表单");
      return;
    }
    
    const checkedKeys = permissionRef.value?.getCheckedKeys();
    const array = checkedKeys.filter(item => typeof item !== 'string' || !item.includes('top'));
    const checkedKeysString = array.join(',');
    
    const formData = {
      rolename: form.rolename,
      remark: form.remark,
      menulist: checkedKeysString
    };

    if (data.doType === 'add') {
      const res = await addRole(formData);
      if (res.code !== 200) {
        ElMessage.error(res.msg || "新增失败");
        return;
      }
      ElMessage.success("新增成功");
      data.open = false;
      fetchTableData();
    } else if (data.doType === 'edit') {
      formData.rolecode = form.rolecode;
      const res = await editRole(formData);
      if (res.code !== 200) {
        ElMessage.error(res.msg || "编辑失败");
        return;
      }
      ElMessage.success("编辑成功");
      data.open = false;
      fetchTableData();
    }
  });
};


const cancel = () => {
  data.open = false
}
const handlePagination = (pageNum) => {
  queryForm.pageNum = pageNum
  fetchTableData()
}

const handlePageSizeChange = () => {
  queryForm.pageNum = 1
  fetchTableData()
}

// 获取所有菜单项
const getAllMenuList = async () => {
  const res = await getMenuList()
  data.permissionOptions = res.rows
}

// 处理编辑
const handleEdit = async (row) => {
   Object.assign(form, row)  // 克隆用户数据，防止混乱
   data.doType = "edit"
   console.log(form)
   // 检查 el-tree 是否有数据
   if (!data.permissionOptions || data.permissionOptions.length === 0) {
     getAllMenuList()
   }
    try {
        const checkedKeys = typeof form.menulist === 'string' ? form.menulist.split(',') : form.menulist;
        // form.formRolename = form.rolename
        // form.remark = form.remark
        // form.rolecode = form.rolecode
        data.title = "菜单分配"
        data.open = true
        await nextTick()
        setTimeout(() => {
            if (permissionRef.value) {
             permissionRef.value?.setCheckedKeys(checkedKeys);
           }
        }, 300) // 确保 el-tree 组件已经渲染完
     } catch (err) {
         console.error('获取用户信息失败:', err)
     }
     
}

// 处理父子联动（严格/非严格选择）
const handleCheckedTreeConnect = async (value, type) => {
  if (type === 'permission') {
    form.permissionCheckStrictly = value;
    console.log('form.permissionCheckStrictly:', form.permissionCheckStrictly);

    await nextTick(); 
    if (!value) {
      permissionRef.value?.setCheckedKeys([]);
    } else {
      permissionRef.value?.setCheckedKeys([]);
    }
  }
};


// 处理全选/全不选
const handleCheckedTreeNodeAll = (value, type) => {
  if (type === 'permission') {
    if (value) {
      // 如果选择全选，独立地选择所有节点，不受父子节点关系影响
      const allIds = data.permissionOptions.map(item => item.id);
      permissionRef.value?.setCheckedKeys(allIds);
    } else {
      // 如果选择全不选，清空所有选中的节点
      permissionRef.value?.setCheckedKeys([]);
    }
  }
}


// 监听树的节点选择变化
const handlePermissionNodeClick = (node, data) => {
  const isChecked = node.checked;
  
  if (!form.permissionCheckStrictly) {
    // 如果不是严格模式，确保父子节点关系不适用
    permissionRef.value?.setChecked(node.data.id, isChecked, false); // 手动切换选中状态
  }
}


</script>

<style>
.app-container {
  padding: 20px;
}

.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}

/* 添加边框样式 */
.tree-border {
  width: 100%;
  border: 1px solid #dcdfe6;  /* 设置边框颜色 */
  border-radius: 4px;         /* 设置圆角 */
  padding: 10px;              /* 设置内边距（可选） */
}

/* 新增、编辑框按钮 */
.dialog-footer {
  display: flex;
  justify-content: center;
  align-items: center;
}

/* tree菜单复选框 */
.el-checkbox:last-of-type {
    margin-right: 5px;
}

/* 解决表数据不能选中复制问题 */
.el-table {
  user-select: text;
}

.el-table__body td {
  user-select: text;
}
</style>
